package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.util.ArrayList;

import java.util.HashMap;


import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyInventoryService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;

import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

/**
 * @author Administrator url-->
 *         http://order.shop.jd.com/order/sSopUp_newYiShipList.action 1.
 *         结算管理--往期结算查询 --》未结算，结算时间为空的单据 2. 结算管理--本期结算查询 --》所有数据 3.
 *         订单管理--订单查询与跟踪 --》已出库所有订单总额
 */

@Service
public class ThirdSellerJDDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {

	private static Logger log = LoggerFactory
			.getLogger(ThirdSellerJDDataCatchServiceImpl.class);
	
	@Autowired
	@Qualifier("fireFox")
	private WebDriverService webDriver;
	
	public WebDriverService getWebDriver() {
		return webDriver;
	}


	public void setWebDriver(WebDriverService webDriver) {
		this.webDriver = webDriver;
	}

	@Autowired
	private SupplyPaymentService paymentService;
	
	@Autowired
	private SupplyInventoryService inventoryService;
	
	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {
		int loginCount = 0;
		// 开始登陆
		this.getWebDriver().getAndPageLoad(baseUrl);

		this.getWebDriver().sendKeys("id", "loginname", username);
		this.getWebDriver().sendKeys("id", "nloginpwd", password);

		// 开始登陆 最多登陆三次（验证码错误情况）
		String loginReturnMess = ""; // 登陆返回信息
		while (loginCount < verifycodeRetryCount) {
			boolean isCome = this.getWebDriver().findElement("id", "o-authcode")
					.isDisplayed();

			if (isCome) {
				this.verifycode();
				// 记录验证码请求次数
				loginCount++;
			}

			this.getWebDriver().clickWaitForPage("id", "loginsubmit");

			boolean loginFlag = this.getWebDriver().getWebDriverWait(30)
					.until(new ExpectedCondition<Boolean>() {
						public Boolean apply(WebDriver d) {
							return d.getTitle().equals("京东商城:商家后台");
						}
					}).booleanValue();

			if (loginFlag) {
				return true;
			}
			try {

				WebElement webLoginReturnMess = this.getWebDriver()
						.findElement("css",
								"#content > div > div.w > div > div.login-box > div.msg-wrap > div.msg-error");

				loginReturnMess = webLoginReturnMess.getText();
				if ("验证码不正确或验证码已过期".trim().equals(loginReturnMess.trim())
						|| "请输入验证码".trim().equals(loginReturnMess.trim())) {
					// 验证码出错，继续登陆
					this.getWebDriver().sendKeys("id", "pwd", password);

					continue;
				} else if ("您输入的账户名与密码不匹配，请重新输入！".trim().equals(
						loginReturnMess.trim())) {

					LogUtils.info(log, this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
							+ "-->username" + username
							+ "登陆失败-->输入的账户名与密码不匹配%s");
					break;
				} else {
					break;
				}
			} catch (Exception e) {
				// 异常可忽略
				LogUtils.info(log, this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
						+ "-->username" + username + "未出现验证码或者用户密码登录错误提示信息");
				break;
			}

		}

		return false;

	}

	
	public void verifycode() throws Exception {
		LogUtils.info(log, this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName() + " 登陆界面包含验证码.");
		WebElement verifyE = this.getWebDriver().findElement("css", "#o-authcode img");

		if (null != verifyE) {

			String code = this.getWebDriver().getVerifyCodeByDMV3(verifyE);
			LogUtils.info(log, this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
					+ "verifyCode->" + code);

			WebElement verifycode = this.getWebDriver().findElement("id", "authcode");

			this.getWebDriver().clearByJS(verifycode);
			// verifycode.clear();
			verifycode.sendKeys(code);

		}

	}

	@Override
	public String catchSupplierName() throws BusinessException {
		// 店铺信息url
		String sellerinfoUrl = "http://seller.shop.jd.com/seller/sellerinfo/seller_info.action";
		this.getWebDriver().get(sellerinfoUrl);
		WebElement divE = this.getWebDriver().findElement("id", "clearBankInfoShow");
		List<WebElement> tdEs = divE.findElements(By.cssSelector("td"));
		if (tdEs == null || tdEs.size() == 0)
			return null;

		return tdEs.get(0).getText();
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		// 店铺信息url
		 BankCardCheck bcc = new BankCardCheck();
		String sellerinfoUrl = "http://seller.shop.jd.com/seller/sellerinfo/seller_info.action";
		this.getWebDriver().getAndPageLoad(sellerinfoUrl);
		WebElement divE = this.getWebDriver().findElement("id", "clearBankInfoShow");
		List<WebElement> tdEs = divE.findElements(By.cssSelector("td"));
		if (tdEs == null || tdEs.size() == 0)
			return null;

		String bankNum = tdEs.get(3).getText();
		
		bcc.setBankNum(bankNum);
		return bcc;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {

		List<TbSlSupplyPayment> ListBefore = new ArrayList<TbSlSupplyPayment>();

		// 往期结算
		getUnBalanceAccountDataBefore(ListBefore);
		// 本期统计和往期统计数据结果不一致，在此修改

		// 本期结算
		TbSlSupplyPayment after = getUnBalanceAccountDataNow();

		ListBefore.add(after);

		// 本期结算变化，所以修改
		// 本期统计和往期统计数据结果不一致，在此修改
		this.getAssistCatchData().getCata().setSettlement(ListBefore);

		List<TbSlSupplyPayment> ListAfter  = new ArrayList<TbSlSupplyPayment>();; 
		// 本期结算变化，所以修改
		ListAfter.add(after);

		//this.getCata().setPayupdate(ListAfter);
		LogUtils.info(log, "getUnpayAccountData()-->执行完毕:");

		return true;
	}

	public void getUnBalanceAccountDataBefore(List<TbSlSupplyPayment> slPList)
			throws BusinessException {
		// 未付款结算单

		String currentAccountUrl = "http://fin.shop.jd.com/financeFee/st_financeStatementList.action";

		this.getWebDriver().getAndPageLoad(currentAccountUrl);// 对账单

		WebElement table = this.getWebDriver().findElement("id", "fsTable");

		WebElement body = table.findElement(By.tagName("tbody"));
		
		List<WebElement> trs = body.findElements(By.tagName("tr"));

		if (null != trs) {
			for (WebElement tr : trs) {

				List<WebElement> tds = tr.findElements(By.tagName("td"));
				if (null != tds && tds.size() > 0) {
					String time = tds.get(9).getText();

					LogUtils.info(log, "time-->" + time);

					
						String balanceOrderId = tds.get(1).getText();
						String balanceStartTime = tds.get(2).getText()
								.substring(0, 10);
						String balanceAccount = tds.get(4).getText();

						TbSlSupplyPayment ordervo = new TbSlSupplyPayment();
						ordervo.setPlatformAccountId(this.getAssistCatchData().getStartMess().getPlatformUser().getId());
						ordervo.setSettlementId(balanceOrderId);
						ordervo.setCreateDate(balanceStartTime);
						if (CommonUtils.isEmpty(time)) {
							ordervo.setSettlementState(TbSlSupplyPayment.WAITPAY);
						}else {
							ordervo.setSettlementState(TbSlSupplyPayment.COMPLETEPAY);
							ordervo.setPayDate(time); 
						}
						
						long longamount = NumberUtils
								.getLongAmount(balanceAccount);
						ordervo.setAmount(longamount);

						slPList.add(ordervo);

						LogUtils.info(log, "JDThird 抓取往期待结算数据：balanceOrderId->"
								+ balanceOrderId + "\n" + "balanceStartTime->"
								+ balanceStartTime + "\n" + "balanceAccount->"
								+ balanceAccount + "\n");

					

				}
			}
		}
	}

	public TbSlSupplyPayment getUnBalanceAccountDataNow()
			throws BusinessException {
		// 未付款结算单
		String currentAccountUrl = "http://fin.shop.jd.com/financeFee/current_finishOrderList.action";
		this.getWebDriver().getAndPageLoad(currentAccountUrl);// 对账单
        
		boolean flag = this.getWebDriver().IsExist("css", "div.account");
		
		if(!flag){
			LogUtils.info(log, "结算单未找到 ");
			return null;
		}
		WebElement banlancetitle = this.getWebDriver().findElement("css", "div.account");

		WebElement h4 = banlancetitle.findElement(By.tagName("h4"));

		String H4 = h4.getText();

		Pattern ph4 = Pattern
				.compile("\\W*:(\\d*)\\s*(\\d{4}-\\d{2}-\\d{2})\\s*\\W\\s*(\\d{4}-\\d{2}-\\d{2})");
		Matcher mh4 = ph4.matcher(H4);
		mh4.find();

		String balanceOrderId = mh4.group(1);
		String balanceStartTime = mh4.group(2);
		String balanceEndTime = mh4.group(3);

		WebElement txt = banlancetitle.findElement(By.cssSelector(".txt"));

		String txT = txt.getText();

		Pattern p = Pattern.compile("(\\d.+\\d)");
		Matcher m = p.matcher(txT);
		m.find();

		String balanceAccount = m.group(1);

		LogUtils.info(log, "JDThird 抓取本期结算数据：balanceOrderId->" + balanceOrderId
				+ "\n" + "balanceStartTime->" + balanceStartTime + "\n"
				+ "balanceEndTime->" + balanceEndTime + "\n"
				+ "balanceAccount->" + balanceAccount + "\n");

		TbSlSupplyPayment ordervo = new TbSlSupplyPayment();
		ordervo.setPlatformAccountId(this.getAssistCatchData().getStartMess().getPlatformUser().getId());
		ordervo.setSettlementId(balanceOrderId);
		ordervo.setCreateDate(balanceStartTime);
		ordervo.setSettlementState(TbSlSupplyPayment.CHECKEDPAY);

		long longamount = NumberUtils.getLongAmount(balanceAccount);

		ordervo.setAmount(longamount);
		LogUtils.info(log, "JDThird 本期已结算未付款金额:" + longamount + "已插入数据库.");
		return ordervo;

	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {
		// 已出库订单

		//String stime = this.getStartMess().getStoreInStartTime();
		//String etime = this.getStartMess().getStoreInEndTime();
		
		/*Map<String, TbSlSupplyInventory> map = this.getStartMess().getStoreIn();
		
		if(null == map){
			map = new HashMap<String, TbSlSupplyInventory>();
		}*/

		Map<String, TbSlSupplyInventory> mapcatch = new HashMap<String, TbSlSupplyInventory>();

		/*String outstoreOrderUrl = "http://order.shop.jd.com/order/sSopUp_newYiShipList.action?oq.id=&oq.startDate="
				+ stime
				+ "+00%3A00%3A00&oq.endDate="
				+ etime
				+ "+23%3A59%3A00&page=";*/
		
		String outstoreOrderUrl = "http://order.shop.jd.com/order/sSopUp_newYiShipList.action?oq.id=&page=";

		int page = 1;
		while (page > 0) {

			String url = outstoreOrderUrl + page;

			this.getWebDriver().getAndPageLoad(url); // 已出库订单

			String current = this.getWebDriver().getText("css", "a.current");
			 
			if(CommonUtils.isEmpty(current)){
				break ;
			}else {
				int cu = Integer.valueOf(current);
				if(page != cu){
					break ;
				}
			}
			
			LogUtils.info(log, "page->" + page + "页加载完成，待 处理数据.");

			List<WebElement> tbodyEs = this.getWebDriver().findElements("css",
					"table.table-list > tbody");

			for (int i = 0; i < tbodyEs.size() - 1; i++) {
				List<WebElement> trEs = tbodyEs.get(i).findElements(
						By.cssSelector("tr.head"));
				if (trEs == null || trEs.size() == 0)
					continue;

				// 遍历出库单各行
				List<WebElement> spanEs = trEs.get(0).findElements(
						By.cssSelector("span"));
				if (spanEs == null || spanEs.size() == 0)
					continue;

				String ItemId = spanEs.get(1).getText().split("：")[1];

				/*if(!CommonUtils.isEmpty(map.get(ItemId))){
					continue;
				}*/
				
				String time = spanEs.get(3).getText().split("：")[1].substring(
						0, 10);

				TbSlSupplyInventory outstorevo = new TbSlSupplyInventory();
				outstorevo.setPlatformAccountId(this.getAssistCatchData().getStartMess().getPlatformUser().getId());
				outstorevo.setItemId(ItemId);
				outstorevo.setItemKey(ItemId);
				String eachTotalCost = spanEs.get(2).getText().split("：")[1];
				long longAmount = NumberUtils.getLongAmount(eachTotalCost);

				outstorevo.setTotalCost(longAmount);

				outstorevo.setStoreDate(time);
				outstorevo.setItemStatus(TbSlSupplyInventory.IN);

				mapcatch.put(ItemId, outstorevo);
			}

			LogUtils.info(log, "page->" + page + "页，插入数据" + mapcatch.size()
					+ "条.");

			page = page + 1;
		}

		List<TbSlSupplyInventory> li = new ArrayList<TbSlSupplyInventory>(
				mapcatch.values());
	
		//inventoryService.removeInventoryCommon(li, map);
		this.getAssistCatchData().getCata().setInstore(li);

		LogUtils.info(log, "getInstoreOrderData:执行完毕");
		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {

		/*String stime = this.getStartMess().getJDstorePayTime();
		String etime = TimeUtils.getCurDate();
		
		List<TbSlSupplyInventory> update = new ArrayList<TbSlSupplyInventory>();
		
		String newUrl = "http://fin.shop.jd.com/finance/newfin/completedOrderListPagingQuery.action?query.orderId=&query.startDate=&query.endDate=&query.billingStartDate="+stime+"&query.billingEndDate="+etime+"&query.statementId=2954555&tagName=completed&page=";
			
		this.getWebDriver().getAndPageLoad(newUrl);// 对账单
		String newUrl = "http://fin.shop.jd.com/finance/newfin/completedOrderListPagingQuery.action?query.orderId=&query.startDate=&query.endDate=&query.billingStartDate="
				+ stime
				+ "&query.billingEndDate="
				+ etime
				+ "&query.statementId=2773574&tagName=completed&page=";
		

		int totalpage = getTotalPage();
		int page = 1;

		while (page <= totalpage) {

			page++;

			List<WebElement> trs = this.getWebDriver().findElements("css",
					"#foTable tbody tr.bg");

			if (null != trs && trs.size() > 0) {
				for (WebElement tr : trs) {
					if (null != tr) {
						List<WebElement> tds = tr
								.findElements(By.tagName("td"));
						if (null != tds && tds.size() > 2) {
							String itemId = tds.get(0).getText();
							String storeDate = tds.get(2).getText();
							TbSlSupplyInventory outstorevo = new TbSlSupplyInventory();
							outstorevo.setPlatformAccountId(this.getStartMess().getPlatformUser()
									.getId());
							outstorevo.setStoreDate(storeDate);
							outstorevo.setItemKey(itemId);
							outstorevo.setItemStatus(TbSlSupplyInventory.PAY);

							update.add(outstorevo);

						}

					}
				}
			} else {
				break;
			}

			this.getWebDriver().get(newUrl + page);

			WaitUtil.waitTimeSeconds(1);
		}

		this.getCata().setInventoryUpdate(update);*/

		LogUtils.info(log, "getOutstoreOrderData:执行完毕");

		return true;
	}

	int getTotalPage() {
		int totalpage = 0;

		List<WebElement> spans = this.getWebDriver()
				.findElements("css",
						"html body#mainframe div#tb1_box.tbl_box div.m.clearfix div.pagin.fr span.text");

		if (spans.size() > 1) {
			WebElement span = spans.get(1);
			String pan = span.getText();
			Pattern p = Pattern.compile("(\\d{1,})");
			Matcher m = p.matcher(pan);
			m.find();
			totalpage = Integer.valueOf(m.group(1));
		}

		return totalpage;
	}
	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
